import os
import sys
import psycopg2
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from redis import StrictRedis,ConnectionPool


class StatusLabel(QWidget):
    def __init__(self,status):
        super(StatusLabel, self).__init__()
        self.status=status
        self.imgs_path = os.path.join(os.path.dirname(__file__), 'imgs')
        self.png200 = os.path.join(self.imgs_path,'200.png')
        self.png404 = os.path.join(self.imgs_path, '404.png')
        self.png503 = os.path.join(self.imgs_path, '503.png')
        self.main_layout=QHBoxLayout()
        self.main_layout.setAlignment(Qt.AlignCenter)
        self.show_label=QLabel('')

        pixmap,show_label=self._getPixmap(self.status)
        self.show_label.setPixmap(pixmap)

        self.status_label=QLabel(show_label)
        self.main_layout.addWidget(self.show_label)
        self.main_layout.addWidget(self.status_label)
        self.setLayout(self.main_layout)


    def _getPixmap(self,status):
        pixmap=None
        show_label=''
        if status==200:
            pixmap=QPixmap(self.png200)
            show_label='正在连接'
        elif status==404:
            pixmap = QPixmap(self.png404)
            show_label = '关机'
        elif status == 503:
            pixmap = QPixmap(self.png503)
            show_label = '断开连接'
        scaled_pixmap=pixmap.scaled(25,25,Qt.KeepAspectRatio)
        return scaled_pixmap,show_label


class IPtable(QTableWidget):

    def __init__(self,sort_department):
        super(IPtable, self).__init__()
        self.sort_department=sort_department

        self.setShowGrid(True)
        self.verticalHeader().setDefaultSectionSize(45)

        # self.verticalHeader().sectionDoubleClicked.connect(self.__v_set)
        self.horizontalHeader().setDefaultSectionSize(100)
        # self.horizontalHeader().sectionDoubleClicked.connect(self.__h_set)
        self.initAll()
        self.head_list=['索引','IP','状态','姓名','部门','备注']
        self.setHorizontalHeaderLabels(self.head_list)
        self.setContextMenuPolicy(Qt.CustomContextMenu)

        # self.customContextMenuRequested.connect(self.rightMenu_Main)
        # self.setEditTriggers(QAbstractItemView.DoubleClicked)
        # self.cellChanged.connect(self._cell_changed)

    def initAll(self):
        """
        初始化，让所有item不为None,初始化时没有表头，注意表头也不能空
        :return:
        """
        self.setColumnCount(6)
        self.setRowCount(6)
        # self.init_head()
        for r in range(self.rowCount()):
            for c in range(self.colorCount()):
                item=QTableWidgetItem()
                item.setText('')
                item.setBackground(QBrush(QColor('#F0FFFF')))
                item.setTextAlignment(Qt.AlignCenter)
                if c==0:
                    item.setFlags(Qt.NoItemFlags)
                self.setItem(r,c,item)

    def init_data(self,data):
        """

        :param data:
        :return:
        """
        if data:
            row_count=len(data)
            self.setRowCount(row_count)
            for i in range(row_count):
                d=data[i] #['索引','IP','状态','姓名','部门','备注']
                ip_id=d['id']
                ip = d['ip']
                status=d['status']
                artist=d['artist']
                department=d['department']
                note=d['note']
                d_list=[]
                d_list.append(ip_id)
                d_list.append(ip)
                d_list.append(status)
                d_list.append(artist)
                d_list.append(department)
                d_list.append(note)
                for c in range(self.columnCount()):
                    # print(i,c)
                    if c!=2:
                        item=QTableWidgetItem()
                        item.setText(d_list[c])
                        item.setTextAlignment(Qt.AlignCenter)
                        # item.setSizeHint(QSize(100,50))
                        self.setItem(i,c,item)
                    else:
                        cell_widget=StatusLabel(status)
                        # item=QTableWidgetItem()
                        self.setCellWidget(i,c,cell_widget)

            # self.sortItems(0)

    def rightMenu_Main(self):
        all_indexes=self.selectionModel().selection().indexes()
        mainMenu = QMenu()
        c=-1
        for i in all_indexes:
            c=i.column()

        if c==1:
            addAccountAction = QAction(u'插入', self)
            addAccountAction.triggered.connect(self.addAccount)
            mainMenu.addAction(addAccountAction)

        if c==3:
            # department_menu=QMenu('设置部门')
            # department_list=['a','b','c','d','e']
            for d in self.sort_department.keys():
                d_action=QAction(d,self)
                # department_menu.addAction(d_action)
                mainMenu.addAction(d_action)
            # department_menu.triggered[QAction].connect(self.setDepartment)#[QAction]
            mainMenu.triggered[QAction].connect(self.setDepartment)
            # mainMenu.addMenu(department_menu)

        mainMenu.exec_(QCursor.pos())

    def addAccount(self):
        cr=self.currentRow()
        print(cr)

    def _add_row(self,int_value):
        """
        槽函数,返回选择的数量.根据数量在尾后添加空行数，注意设置垂直表头
        :param int_value:
        :return:
        """
        ori_count=self.rowCount()

        self.setRowCount(self.rowCount()+int_value)
        for r in range(ori_count,self.rowCount()):
            v_item=QTableWidgetItem()
            v_item.setText(str(r+1))
            self.setVerticalHeaderItem(r,v_item)
            for c in range(self.columnCount()):
                item=QTableWidgetItem()
                item.setText('')
                item.setBackground(QBrush(QColor('#F0FFFF')))
                item.setTextAlignment(Qt.AlignCenter)
                self.setItem(r,c,item)

    def set_data(self,data):
        """
        设置data数据
        :param data:  {}
        :return:
        """
        if data:
            pass


    def rightMenu(self):
        mainMenu=QMenu()
        mainMenu.exec_(QCursor.pos())


class StatusWindow(QWidget):

    def __init__(self):
        super(StatusWindow, self).__init__()
        self.sort_department={'01美术':1,'02模型':2,'03跟踪':3,'04动画':4,'05场景':5,'06灯光':6,'07特效一':7,'07特效二':8,
                                     '08合成一':9,'08合成二':10,'09包装':11,'10剪辑':12,'11调色':13,'12TD':14,'13虚拟':15,'14视效':16}
        self.big_font=QFont('',25,65)
        self.setMinimumWidth(650)
        self.setMinimumHeight(800)
        self.setWindowTitle('服务状态')
        self.main_layout=QVBoxLayout()
        self.main_layout.setSpacing(25)
        self.main_layout.setAlignment(Qt.AlignCenter)
        self.main_label=QLabel('服务监听状态')
        self.main_label.setFont(self.big_font)
        self.main_label.setAlignment(Qt.AlignCenter)
        self.iptable=IPtable(self.sort_department)
        self.main_layout.addWidget(self.main_label)
        self.main_layout.addWidget(self.iptable)
        self.setLayout(self.main_layout)

        # self.iptable.init_data(self.get_ip_data())
        self.update_data()

    def update_data(self):
        ip_data=self.get_ip_data()   #这是本地的记录的数据[{'id': '1', 'artist': '张洲', 'ip': '192.168.1.88', 'department': '12TD', 'note': None, 'status': '404'}
        status_data=self.get_redis_status()  #这里是所有的1-255的ip状态{'192.168.1.255': 404, '192.168.1.19': 404, '192.168.1.20': 404,...}
        print('status_data:',status_data)
        last_data_list=[]
        for k,v in status_data.items():
            status=v
            if k in ip_data.keys():
                data=ip_data[k]
                data['status']=status  #更新状态
                last_data_list.append(data)
            else:  #当本地没有该ip时，说明该ip没有注册在里面
                pass
        sorted_data=sorted(last_data_list,key=lambda x:int(x['id']))
        self.iptable.init_data(sorted_data)
        # return last_data_list



    def init_handler(self):
        time_connect = time_cursor = None
        try:
            time_connect = psycopg2.connect(database='taskprogress',
                                            user='timeaxis',
                                            password='timeaxis',
                                            host='192.168.1.222',
                                            port=5432)
            time_cursor = time_connect.cursor()
        except Exception as init_handler_ERR:
            print(str(init_handler_ERR))

        return time_connect, time_cursor

    def get_ip_data(self):
        ip_data = {}
        try:
            time_connect, time_cursor = self.init_handler()
            select_sql = "select id,artist,ip,department,note from account"
            time_cursor.execute(select_sql)
            result = time_cursor.fetchall()
            if result:
                for i in result:
                    data={} #['索引','IP','状态','姓名','部门','备注']
                    data['id'] = str(i[0])
                    data['artist'] = i[1]
                    data['ip'] = i[2]
                    data['department'] = i[3]
                    data['note']=i[4]
                    data['status']=404  #默认关机状态
                    ip_data[data['ip']]=data
                    # ip_data.append(data)
        except Exception as get_ip_data_ERR:
            print('get_ip_data_ERR:', str(get_ip_data_ERR))
        finally:
            time_connect.close()
        print('ip_data:',ip_data)
        return ip_data

    def get_redis_status(self):
        data={}
        try:
            pool=ConnectionPool(host='192.168.1.83',port=6379,password='123456',db=0)
            rs=StrictRedis(connection_pool=pool)
            data=rs['ip_list']
            data=eval(data)
        except Exception as get_redis_status_ERR:
            print('get_redis_status_ERR:',str(get_redis_status_ERR))
        # print(data)
        return data


if __name__ == '__main__':
    app=QApplication(sys.argv)
    # sl=StatusLabel()
    sl = StatusWindow()
    sl.show()
    sys.exit(app.exec_())
